package cn.yangliu.nacos.oauth2.web;

import javax.servlet.http.HttpServletRequest;

import cn.yangliu.nacos.comm.enums.GlobalResultCode;
import cn.yangliu.nacos.comm.ex.GlobalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@FrameworkEndpoint
public class RevokeTokenEndpoint {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(RevokeTokenEndpoint.class);

	/**
	 * The Consumer token services.
	 */
	@Autowired
    @Qualifier("consumerTokenServices")
    ConsumerTokenServices consumerTokenServices;

	/**
     * Custom logout.
     *
     * @param request the request
     */
	@GetMapping("/oauth/logout")
    @ResponseBody
    public void revokeToken(HttpServletRequest request) {
        /**
         * 获取授权用户
         */
        String authorization = request.getHeader("authorization");
        String accessToken = "";
        /**
         * 获取进入的token
         */
        if (authorization != null && authorization.contains("bearer")) {
            accessToken = authorization.substring("bearer".length() + 1);
        }
        /**
         * 清除token实现退出操作
         */
        if (!consumerTokenServices.revokeToken(accessToken)) {
            LOGGER.error("revokeToken {} failed!", accessToken);
            throw new GlobalException(GlobalResultCode.REVOKE_TOKEN_FAILED);
        }
    }

}
